/*
 * Copyright 2019 Flipkart Internet Pvt. Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.flipkart.ohos.proteus;

import ohos.app.AbilityContext;

import java.util.HashMap;
import java.util.Map;

/**
 * Proteus
 *
 * @author aditya.sharat
 */

public final class Proteus {
    public final FunctionManager functions;

    private final Map<String, Type> types;

    private final Map<String, ViewTypeParser> parsers;

    Proteus(Map<String, Type> types, final Map<String, Function> functions) {
        this.types = types;
        this.functions = new FunctionManager(functions);
        this.parsers = map(types);
    }

    public boolean has(String type) {
        return types.containsKey(type);
    }

    public ViewTypeParser.AttrSet.Attribute getAttributeId(String name, String type) {
        return types.get(type).getAttributeId(name);
    }

    private Map<String, ViewTypeParser> map(Map<String, Type> types) {
        Map<String, ViewTypeParser> parsers = new HashMap<>(types.size());
        for (Map.Entry<String, Type> entry : types.entrySet()) {
            parsers.put(entry.getKey(), entry.getValue().parser);
        }
        return parsers;
    }

    public ProteusContext createContext(AbilityContext base) {
        return createContextBuilder(base).build();
    }

    public ProteusContext.Builder createContextBuilder(AbilityContext base) {
        return new ProteusContext.Builder(base, parsers, functions);
    }

    public static class Type {
        public final int id;
        public final String type;
        public final ViewTypeParser parser;

        private final ViewTypeParser.AttrSet attributes;

        Type(int id, String type, ViewTypeParser parser, ViewTypeParser.AttrSet attributes) {
            this.id = id;
            this.type = type;
            this.parser = parser;
            this.attributes = attributes;
        }

        public ViewTypeParser.AttrSet.Attribute getAttributeId(String name) {
            return attributes.getAttribute(name);
        }
    }
}
